package com.anxin.service.impl;

import cn.hutool.core.util.IdUtil;
import com.anxin.entity.User;
import com.anxin.mapper.UserMapper;
import com.anxin.service.UserService;
import com.anxin.security.jwt.JwtTokenProvider;
import com.anxin.common.Result;
import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private JwtTokenProvider jwtTokenProvider;
    
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result<Boolean> register(User user) {
        if (lambdaQuery().eq(User::getUsername, user.getUsername()).count() > 0) {
            return Result.error("用户名已存在");
        }
        user.setId(IdUtil.fastSimpleUUID());
        user.setPassword(DigestUtil.md5Hex(user.getPassword()));
        user.setStatus(1);
        user.setRole("PATIENT");
        boolean saved = save(user);
        return saved ? Result.success(true) : Result.error("注册失败");
    }

    @Override
    public Result<String> login(User user) {
        User loginUser = lambdaQuery().eq(User::getUsername, user.getUsername()).one();
        if (loginUser == null || !loginUser.getPassword().equals(DigestUtil.md5Hex(user.getPassword()))) {
            return Result.error("用户名或密码错误");
        }
        if (loginUser.getStatus() != null && loginUser.getStatus() == 0){
            return Result.error("账号已被禁用");
        }
        
        String token = jwtTokenProvider.generateToken(loginUser.getUsername());
        redisTemplate.opsForValue().set("login:token:" + token, loginUser.getId(), 86400, TimeUnit.SECONDS);
        return Result.success(token);
    }

    @Override
    public List<User> getAllUsers() {
        //将密码不返回给前端
        List<User> users = baseMapper.selectList(null);
        users.forEach(user -> user.setPassword(null));
        return users;
    }
}
